import 'package:flutter/cupertino.dart';
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';

class CustomCamera extends StatefulWidget {
  const CustomCamera({super.key});

  @override
  _CustomCameraState createState() => _CustomCameraState();
}

class _CustomCameraState extends State<CustomCamera> {
  late CameraController _controller;
  late List<CameraDescription> _cameras;
  late Future<void> _initializeControllerFuture;


  @override
  void initState() {
    super.initState();
    _initializeCamera();
  }

  Future<void> _initializeCamera() async {
    try {
      _cameras = await availableCameras();
      _controller = CameraController(_cameras[0], ResolutionPreset.medium);
      // 使用第一个摄像头并设置分辨率
      _initializeControllerFuture = _controller.initialize(); // 获取所有可用摄像头列表
      if (!mounted) return; // 检查是否还有widget在渲染中，以避免在dispose后调用setState
      setState(() {}); // 更新状态以触发UI重建

    } on CameraException catch (e) {
      print('Error initializing camera: $e'); // 打印错误信息。
    } // 初始化控制器

  }

  @override
  void dispose() {
    _controller.dispose(); // 清理资源
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // if (_controller == null || !_controller.value.isInitialized) {
    //   return Center(child: CircularProgressIndicator()); // 显示加载指示器，直到相机初始化完成
    // }
    // return AspectRatio(
    //   aspectRatio: _controller.value.aspectRatio, // 保持相机的宽高比
    //   child: CameraPreview(_controller), // 使用CameraPreview显示相机预览
    // );
    return FutureBuilder<void>(
      future: _initializeControllerFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          // If the Future is complete, display the preview.
          return AspectRatio(
            aspectRatio: _controller.value.aspectRatio, // 保持相机的宽高比
            child: CameraPreview(_controller), // 使用CameraPreview显示相机预览
          );
        } else {
          // Otherwise, display a loading indicator.
          return const Center(child: CircularProgressIndicator());
        }
      },
    );
  }
}
